import 'package:flutter/material.dart';
import 'package:http/http.dart';

/**
 * 状态管理分为局部状态管理和全局(大的局部)管理,其实所有的一切归根到底都是类似调用setState的逻辑,这里简单的梳理了一下全局状态管的学习思路
 * 关于InheritedWidget其实就是一个特殊的Widget,被单独放到了一个数组里边(本质是这对应的element,
 * 放到了一个单独的数组里),其实这里这样做的好处是查找时候很方便,因为elementTree有时候是很庞大的,
 * 从最后一个往上查找找到对应的element是比较浪费资源的,这里定义一个widget,专门用来处理这种树结构传输数据,
 * 查找的时候只需要从这一堆中查找就可以了, InheritedWidget由此诞生
 */

class StateManagementDemo extends StatefulWidget {
  const StateManagementDemo({super.key});

  @override
  State<StateManagementDemo> createState() => _StateManagementDemoState();
}

class _StateManagementDemoState extends State<StateManagementDemo> {
  int _count = 0;

  void _increaseCount(){
    setState(() {
      _count += 1;
    });
    print('$_count');
  }

  @override
  Widget build(BuildContext context) {
    return CounterProvider(
      count: _count,
      increaseCount: _increaseCount,
      child: Scaffold(
        appBar: AppBar(
          title: Text('StateManagementDemo'),
          elevation: 0.0,
        ),
        body: CounterWrapper(),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: _increaseCount,
        ),
      ),
    );
  }
}

class CounterWrapper extends StatelessWidget {
  const CounterWrapper( {super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Counter(),
      );
  }
}

class Counter extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final int count = CounterProvider.of(context)!.count;
    final VoidCallback increaseCount = CounterProvider.of(context)!.increaseCount;

    return ActionChip(label: Text('$count'),onPressed: increaseCount);
  }
}

class CounterProvider extends InheritedWidget {
  final int count;
  final VoidCallback increaseCount;
  final Widget child;
  
  const CounterProvider({required this.count,required this.increaseCount,required this.child}) : super(child: child);

  static CounterProvider? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<CounterProvider>();
  }

  @override
  bool updateShouldNotify(CounterProvider oldWidget) {
    return true;
  }
}